setwd('/Users/samferguson/Development/smfrgsn-devel/EmotionExp/CodeProcessing')
source('processTS.R');
library(xlsx)
fnlen <- c(16.0609, 17.4497, 19.9488, 19.3082, 15.6175, 20.5530, 19.8810,  7.0139, 17.0833, 21.5696, 16.0110, 15.4879, 10.3249,   27.3807,   21.5624,   23.3500,   11.1151,   19.5265,   19.0329);
fn <- c("Excited1_ToyStory.mp3", "Angry1_UpAUD.mp3", "Angry4_ToyStory3.mp3", "Angry5_ToyStory3.mp3", "Calm1_Nemo.mp3","Calm2_Nemo.mp3","Calm3_Nemo.mp3","Excited4_Cars.mp3","Excited5_Cars.mp3","Excited3_Up.mp3","Happy1_CarsAUD.mp3","Happy2_Monsters.mp3","Happy3_Up.mp3","Sad1_Cars.mp3","Sad6_ToyStory3.mp3","Sad7_ToyStory3.mp3","Scared1_Up.mp3","Scared2_Up.mp3","Scared4_Up.mp3")


for (i in 0:18){
    	
    # Load dataset
    d = read.table(paste(getwd(),"/","excerpt",i,"TS.txt",sep=""),sep="\t",header=TRUE)
    
    # Fix excerpt12		
   	if (i ==12){
    		d$Time = d$Time	- 0.418;
    		d = subset(d,Time > 0);
    		# Curtail to length
  	  	d = subset(d,Time<=fnlen[i+1]-0.418);
    	
    	} else {
  
    	# Curtail to length
    	d = subset(d,Time<=fnlen[i+1]);
  	}
    	
     dl1 = subset(d, Level %in% c("Level1A","Level1B"));
	 outl1E = processTS(dl1,"Expressed");
	 outl1F = processTS(dl1,"Felt");
	 
    #makeLocusMatchPlot(outE,outF,i,fn)
	write.xlsx(outl1F,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level1Felt", row.names=FALSE,col.names=FALSE)
	write.xlsx(outl1E,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level1Expressed", append=TRUE,row.names=FALSE,col.names=FALSE)  
	
	if(i > 0){
     dl2 = subset(d, Level %in% c("Level2"));
	 outl2E = processTS(dl2,"Expressed");
	 outl2F = processTS(dl2,"Felt");

     dl3 = subset(d, Level %in% c("Level3"));
	 outl3E = processTS(dl3,"Expressed");
	 outl3F = processTS(dl3,"Felt");
	write.xlsx(outl2F,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level2Felt",      append=TRUE,row.names=FALSE,col.names=FALSE)
	write.xlsx(outl2E,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level2Expressed", append=TRUE,row.names=FALSE,col.names=FALSE)  	
	write.xlsx(outl3F,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level3Felt",      append=TRUE,row.names=FALSE,col.names=FALSE)
	write.xlsx(outl3E,file=paste("Children2010/Timeseries", fn[i+1],".xlsx",sep=""),sheetName="Level3Expressed", append=TRUE,row.names=FALSE,col.names=FALSE)  	

	
    }
    	
	rm(outl1E, outl1F, outl2E, outl2F, outl3E, outl3F)
	rm(d,dl1,dl2,dl3)
#	write.table(outF,file=paste("TimeseriesFelt", fn[i+1],".txt",sep=""),row.names=FALSE,col.names=FALSE,sep="\t")
#	write.table(outE,file=paste("TimeseriesExpressed", fn[i+1],".txt",sep=""),row.names=FALSE,col.names=FALSE,sep="\t")  	

}

